package com.leixin.controller;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.leixin.service.BaseService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;

/**
 * @Description: TODO
 * @Date : 2020/4/20
 * @Company : TODO
 * @Author : LeiXin
 */
public abstract class BaseController<M extends BaseMapper<T>, T extends Model<?>, PK extends Serializable> {

    @Autowired
    protected BaseService<M, T> baseService;

    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "size", paramType = "query", value = "页面大小", required = false),
            @ApiImplicitParam(name = "current", paramType = "query", value = "页码，从1开始", required = false)
    })
    @ApiOperation(value = "分页查询", notes = "分页查询： 分页类型数据只在分页时返回", nickname = "Model_page")
    public <E extends IPage<T>> E page(E page, T w) {
        return baseService.page(page, Wrappers.lambdaQuery(w));
    }

    @GetMapping
    @ApiOperation(value = "条件查询", notes = "条件查询", nickname = "Model_getAll")
    public List<T> findAll(T t) {
        return baseService.list(Wrappers.lambdaQuery(t));
    }

    @GetMapping("{id}")
    @ApiOperation(value = "查询", notes = "根据ID查询", httpMethod = "GET", nickname = "Model_getById")
    public T getById(@PathVariable("id") PK id) {
        return baseService.getById(id);
    }

    @PostMapping
    @ApiOperation(value = "保存", notes = "保存", httpMethod = "POST", nickname = "Model_save")
    public boolean save(@RequestBody T t) {
        return baseService.save(t);
    }

    @PostMapping("batch")
    @ApiOperation(value = "批量保存", notes = "批量保存", httpMethod = "POST", nickname = "Model_saveBatch")
    public boolean saveBatch(@RequestBody List<T> models) {
        return baseService.saveBatch(models);
    }

    @PutMapping
    @ApiOperation(value = "更新", notes = "更新", httpMethod = "PUT", nickname = "Model_update")
    public boolean update(@RequestBody T t) {
        return baseService.updateById(t);
    }

    @DeleteMapping
    @ApiOperation(value = "删除", notes = "删除", httpMethod = "DELETE", nickname = "Model_del")
    public boolean del(PK id) {
        return baseService.removeById(id);
    }

    @DeleteMapping("batch")
    @ApiOperation(value = "批量删除", notes = "批量删除", httpMethod = "DELETE", nickname = "Model_dels")
    public boolean dels(@RequestBody List<PK> ids) {
        return baseService.removeByIds(ids);
    }

}
